#include "DXUT.h"
#include "Updater.h"

DWORD WINAPI Updater::run( LPVOID pParam )
{
	Updater* This = (Updater*) pParam;

	if ( ( This == NULL )  || ( This->m_pWorld == NULL ) ) return 1; 

	ULONGLONG lastTime = GetTickCount64();
	
	for (uint i = 0; ; i++) {
		if (This->m_Terminate) break;

		ULONGLONG curTime = GetTickCount64();

		//printf("%d\n", curTime - lastTime);
		if (curTime >= lastTime + 50) {
			lastTime  = curTime;
			//if ((i % 100) == 0)
			//	srand(static_cast<UINT>(curTime));

			//This->m_pWorld->update();

			if (This->m_Terminate) break;
#ifdef RENDER
			if (This->m_pWorld->renewDirty(false) < 0)
				Sleep(1000);
#endif
		} else {
			Sleep(static_cast<DWORD>((lastTime + 50) - curTime));
		}
	}

	delete This;	
	return 0;
}

Updater::Updater(World* pWorld) {
	m_pWorld		= pWorld;
	m_Terminate		= false;
	
	m_Thread_Handle = CreateThread( NULL, 0, run, this, 0, NULL); 

}

Updater::~Updater() {
	m_pWorld		= NULL;
}

DWORD WINAPI TickUpdater::run( LPVOID pParam )
{
	TickUpdater* This = (TickUpdater*) pParam;

	if ( ( This == NULL )  || ( This->m_pWorld == NULL ) ) return 1; 

	//This->m_pQueue		= new Updatequeue(This->m_pWorld);

	ULONGLONG lastTime = GetTickCount64();
	for (;;) {
		if (This->m_Terminate) {
			break;
		}

		ULONGLONG curTime = GetTickCount64();

		if (curTime >= lastTime + 50) {
			lastTime  = curTime;
			This->m_pQueue->work();

			if (This->m_Terminate) break;
#ifdef RENDER
			This->m_pWorld->renewDirty(false);
#endif
		} else {
			Sleep(static_cast<DWORD>((lastTime + 50) - curTime));
		}
	}
	
	delete This;

	return 0;
}

void TickUpdater::setValue( void * userData ) {
	m_pQueue->updateBlock(*((QueElement*)userData));
}

TickUpdater::TickUpdater(World* pWorld) {
	m_pWorld		= pWorld;
	m_Terminate		= false;
	m_pQueue		= new Updatequeue(pWorld);
	m_pQueue->load();
	m_Thread_Handle = CreateThread( NULL, 0, run, this, CREATE_SUSPENDED, NULL); 
}

TickUpdater::~TickUpdater() {
	delete m_pQueue;
	m_pQueue		= NULL;
	m_pWorld		= NULL;
}